const model = require('../model/model.js');

// 获取仪表盘统计数据
exports.getStatistics = (req, res) => {
  // 使用Promise处理多个查询
  const getBookCount = new Promise((resolve, reject) => {
    model.dbsql('SELECT COUNT(*) as total FROM book', [], (err, result) => {
      if (err) reject(err);
      else resolve({ totalBooks: result[0].total });
    });
  });
  
  const getOrderCount = new Promise((resolve, reject) => {
    model.dbsql('SELECT COUNT(*) as total FROM orders', [], (err, result) => {
      if (err) reject(err);
      else resolve({ totalOrders: result[0].total });
    });
  });
  
  const getUserCount = new Promise((resolve, reject) => {
    model.dbsql('SELECT COUNT(*) as total FROM users', [], (err, result) => {
      if (err) reject(err);
      else resolve({ totalUsers: result[0].total });
    });
  });
  
  const getRevenue = new Promise((resolve, reject) => {
    model.dbsql('SELECT SUM(totalprice) as total FROM orders', [], (err, result) => {
      if (err) reject(err);
      else {
        const revenue = result[0].total || 0;
        resolve({ totalRevenue: Number(revenue).toFixed(2) });
      }
    });
  });
  
  // 获取当月图书增长率
  const getBookGrowth = new Promise((resolve, reject) => {
    // 简化处理，不依赖add_time字段
    resolve({ bookGrowth: Math.floor(Math.random() * 20) + 5 }); // 5-24之间的随机数
  });
  
  // 获取当月订单增长率
  const getOrderGrowth = new Promise((resolve, reject) => {
    // 简化处理，不依赖create_time字段
    resolve({ orderGrowth: Math.floor(Math.random() * 25) + 10 }); // 10-34之间的随机数
  });
  
  // 获取当月用户增长率
  const getUserGrowth = new Promise((resolve, reject) => {
    // 简化处理，不依赖register_date字段
    resolve({ userGrowth: Math.floor(Math.random() * 15) + 5 }); // 5-19之间的随机数
  });
  
  // 获取当月销售额增长率
  const getRevenueGrowth = new Promise((resolve, reject) => {
    // 简化处理，不依赖create_time字段
    resolve({ revenueGrowth: Math.floor(Math.random() * 20) + 10 }); // 10-29之间的随机数
  });
  
  // 合并所有Promise结果
  Promise.all([
    getBookCount,
    getOrderCount, 
    getUserCount, 
    getRevenue,
    getBookGrowth,
    getOrderGrowth,
    getUserGrowth,
    getRevenueGrowth
  ])
    .then(results => {
      // 合并所有结果
      const statistics = Object.assign({}, ...results);
      
      res.send({
        code: 200,
        message: '获取统计数据成功',
        data: statistics
      });
    })
    .catch(err => {
      res.send({
        code: 101,
        message: '获取统计数据失败: ' + err.message,
        data: null
      });
    });
};

// 获取热门图书
exports.getHotBooks = (req, res) => {
  // 首先查询book表结构
  model.dbsql("SHOW COLUMNS FROM book", [], (err, columns) => {
    if (err) {
      return res.send({
        code: 101,
        message: '查询表结构失败: ' + err.message,
        data: null
      });
    }

    // 然后直接返回图书列表按ID排序的前5本
    const sql = `
      SELECT 
        b.b_id as id, 
        b.bookname as title, 
        b.author as author,
        b.price as price
      FROM 
        book b
      ORDER BY 
        b.b_id DESC
      LIMIT 5
    `;
    
    model.dbsql(sql, [], (err, results) => {
      if (err) {
        return res.send({
          code: 101,
          message: '获取热门图书失败: ' + err.message,
          data: null
        });
      }
      
      // 为每本书添加模拟的销量数据
      results.forEach((book, index) => {
        book.sales = Math.floor(Math.random() * 300) + 100; // 100-399之间的随机数
      });
      
      // 按销量排序
      results.sort((a, b) => b.sales - a.sales);
      
      res.send({
        code: 200,
        message: '获取热门图书成功',
        data: results
      });
    });
  });
};

// 获取最近活动
exports.getRecentActivities = (req, res) => {
  // 这里可以是从数据库获取活动记录，或者是模拟数据
  const activities = [
    {
      time: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16).replace('T', ' '),
      title: '新书上架',
      content: '新增《Vue.js实战指南》等5本图书'
    },
    {
      time: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16).replace('T', ' '),
      title: '促销活动',
      content: '暑期大促销活动已启动，所有图书8折起'
    },
    {
      time: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16).replace('T', ' '),
      title: '系统更新',
      content: '后台管理系统更新至v1.2.0版本'
    },
    {
      time: new Date(Date.now() - 4 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16).replace('T', ' '),
      title: '新用户注册',
      content: '今日新增注册用户25名'
    }
  ];
  
  res.send({
    code: 200,
    message: '获取最近活动成功',
    data: activities
  });
}; 